<template>
  <div>
    <!--增加或更新的表单弹窗-->
    <div style="text-align: left; margin: 10px">
      <el-button size="mini"  type="primary" @click="toAdd">
        添加
      </el-button>
    </div>

    <el-dialog :title=formTitle :visible.sync="formDialogVisible">
      <el-form ref="form" :model="formData" :rules="rules" size="large" label-width="100px">
        <el-form-item label="手机" prop="phone">
          <el-input v-model="formData.phone" :maxlength="11"  autofocus></el-input>
        </el-form-item>
        <el-form-item label="姓名" prop="name">
          <el-input v-model="formData.name" :maxlength="4"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button @click="resetForm">重置</el-button>
          <el-button type="primary" @click="handelConfirm">确定</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>

    <!--列表-->
    <div style="margin: 0 10px; text-align: left;">
      <el-table
              :data="workers.slice((currentPage-1) * pageSize, currentPage * pageSize)"
              stripe
              :default-sort="{prop: 'name', order: 'ascending'}">

        <el-table-column prop="phone" label="手机"></el-table-column>
        <el-table-column prop="name" label="姓名" sortable></el-table-column>
        <el-table-column label="微信头像" sortable>
          <template slot-scope="scope">
            <img :src="scope.row.wxAvatar" style="width: 40px; height: 40px;" alt="">
          </template>
        </el-table-column>
        <el-table-column label="冻结状态">
          <template slot-scope="scope">
            <el-switch
                    v-model="scope.row.status"
                    active-color="green"
                    inactive-color="red"
                    @change="(value) => commitStatusChange(value, scope.row)">
            </el-switch>
          </template>
        </el-table-column>

        <el-table-column label="操作"  width="170">
          <template slot-scope="scope">
            <el-button @click="resetPassword(scope.row.id)" type="text" size="mini">重置密码</el-button>
            <el-button @click="toEdit(scope.row)" type="text" size="mini">编辑</el-button>
            <el-button type="text" size="mini" @click="toDelete(scope.row.id)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <!--分页组件-->
      <el-row style="float: right">
        <el-pagination
                @current-change="currentPage => this.currentPage = currentPage"
                @size-change="pageSize => this.pageSize = pageSize"
                :current-page.sync="currentPage"
                :page-sizes="[5, 10, 20, 30, 50, 100]"
                :page-size.sync="pageSize"
                layout=" total, sizes, prev, pager, next, jumper"
                :total="workers.length">
        </el-pagination>
      </el-row>

    </div>
  </div>
</template>

<script>
  import {addWorker, deleteWorkers, getAllWorkers, updateWorker,resetPassword,updateWorkerStatus} from "@/api/modules/app/workerApi.js";

  export default {
    name: "workerComponent",
    data() {
      return {
        currentPage: 1,
        pageSize: 10,
        workers: [],
        formDialogVisible: false,
        formTitle: '添加',
        formData: {
          phone: null, name: null
        },
        rules: {
          phone: [
            {required: true, message: '姓名不能为空', trigger: 'blur'},
            {pattern: /^1(3|4|5|7|8)\d{9}$/, message: "手机号格式不正确"}
          ],
          name: [
            {required: true, message: '姓名不能为空', trigger: 'blur'}
          ]
        }
      }
    },
    mounted() {
      this.getAllWorkers()
    },
    methods: {
      //获取所有数据
      getAllWorkers() {
        getAllWorkers().then(result => {
          this.workers = result.data
        })
      },
      // 重置表单
      resetForm() {
        // 手动重置 不然数据被绑定在toEdit时深克隆出来的对象
        this.formData = {
          phone: null, name: null
        }
      },
      // 增加
      toAdd() {
        this.resetForm()
        this.formDialogVisible = true
        this.formTitle = '添加'
      },
      // 删除
      toDelete(id) {
        let that = this;
        this.$confirm("提示", "是否删除", {}).then(() => {
          deleteWorkers([id]).then(() => {
            this.$notify.success("删除成功");
            that.getAllWorkers();
          })
        }).catch(() => {
        })
      },
      // 编辑
      toEdit(selectedWorker) {
        // 深拷贝一个对象 不然在表格显示的数据会受到印象
        this.formData = JSON.parse(JSON.stringify(selectedWorker));
        this.formData.phone =  '' + selectedWorker.phone; // 强转成string
        this.formDialogVisible = true
        this.formTitle = '更新'
      },
      // 提交表单
      handelConfirm() {
        this.$refs['form'].validate(valid => {
          console.log(this.formTitle)
          if (!valid)
            return

          this.formDialogVisible = false;
          if (this.formTitle.startsWith('添加')) {
            addWorker(this.formData).then(result => {
              this.$notify.success("添加成功");
              this.getAllWorkers()
            })
          } else if (this.formTitle.startsWith('更新')) {
            updateWorker(this.formData).then(result => {
              this.$notify.success("更新成功");
              this.getAllWorkers()
            })
          }
        })
      },
      // 冻结账号
      commitStatusChange(value, worker) {
        this.$confirm(value === false ? '冻结账号?' : '激活账号').then(() => {
          updateWorkerStatus(worker.id).then(() => {
            this.$notify.success(value === false ? "已冻结" : "已激活")
          }).catch(() => {
            worker.status = !worker.status;
          })
        }).catch(() => {
          worker.status = !worker.status;
        })
      },
      // 重置密码
      resetPassword(id){
        this.$confirm("重置密码?").then(() => {
          resetPassword(id).then(()=> {
            this.$notify.success("密码重置成功")
          })
        }).catch(() =>{})
      }
    }
  }
</script>
